package hc.um.action;

import hc.um.service.UserService;
import hc.um.Employee;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class LoginServlet
 */
@WebServlet(description = "user login system", urlPatterns = { "/LoginService" })
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	private UserService userService = new UserService();

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public LoginServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		System.out.println("user=" + request.getParameter("user"));
		System.out.println("pwd=" + request.getParameter("pwd"));
		
		this.checkUser(request, response);
	}

	public void checkUser(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		Employee employee = null;
		if ((employee = userService.checkUser(request.getParameter("username"),
				request.getParameter("password"))) != null) {
			// response.sendRedirect("./user/officermain.html");
			response.getWriter().write(creatXmlTextLogin("Success", employee));
		} else {
			response.getWriter().write(creatXmlTextLogin("Fail", employee=new Employee()));
		}
	}

	public String creatXmlTextLogin(String result, Employee wemployee) {
		String xmltext = null;

		xmltext = "<login><result>" + result + "</result><userid>"
				+ wemployee.getID() + "</userid><roleId>"
				+ wemployee.getRoleID() + "</roleId></login>";
		System.out.println("xmltext="+xmltext);
		
		return xmltext;
	}
}
